#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
调试增强版LSTM-CRF模型预测结果全是0的问题
"""

import os
import sys
import torch
import numpy as np

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.append(project_root)

def debug_enhanced_lstm_crf_prediction():
    """调试增强版LSTM-CRF模型预测"""
    try:
        # 设置设备
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        print(f"使用设备: {device}")
        
        # 模型文件路径
        model_path = os.path.join(project_root, 'scripts', 'plw', 'enhanced_lstm_crf_model.pth')
        
        if not os.path.exists(model_path):
            print(f"模型文件不存在: {model_path}")
            return
        
        print(f"加载模型: {model_path}")
        
        # 加载模型
        checkpoint = torch.load(model_path, map_location=device)
        print(f"检查点键: {checkpoint.keys()}")
        
        # 获取模型配置
        if 'model_config' in checkpoint:
            config = checkpoint['model_config']
            print(f"模型配置: {config}")
            
            # 导入模型类
            from algorithms.enhanced_lstm_crf import EnhancedLstmCRFModel
            
            # 创建模型
            model = EnhancedLstmCRFModel(**config)
            print(f"模型创建成功")
            
            # 加载模型权重
            if 'model_state_dict' in checkpoint:
                model.load_state_dict(checkpoint['model_state_dict'])
                print("模型权重加载成功")
            else:
                print("检查点中缺少model_state_dict")
                return
            
            model.to(device)
            model.eval()
            print("模型设置为评估模式")
            
            # 创建测试输入数据
            # 使用随机数据进行测试
            batch_size = 1
            seq_len = 10
            input_dim = config.get('input_dim', 10)
            
            # 创建符合排列5特征的输入数据（0-9范围）
            test_input = torch.randint(0, 10, (batch_size, seq_len, input_dim)).float().to(device)
            print(f"测试输入形状: {test_input.shape}")
            print(f"测试输入数据: {test_input}")
            
            # 进行预测
            with torch.no_grad():
                predictions = model(test_input)
                print(f"预测结果类型: {type(predictions)}")
                print(f"预测结果: {predictions}")
                
                if isinstance(predictions, list):
                    print(f"预测结果长度: {len(predictions)}")
                    if len(predictions) > 0:
                        print(f"第一个预测结果类型: {type(predictions[0])}")
                        print(f"第一个预测结果: {predictions[0]}")
                        if isinstance(predictions[0], list) and len(predictions[0]) > 0:
                            print(f"第一个预测结果的第一个元素: {predictions[0][0]}")
                elif isinstance(predictions, torch.Tensor):
                    print(f"预测结果形状: {predictions.shape}")
                    
        else:
            print("模型检查点中缺少model_config")
            
    except Exception as e:
        print(f"测试过程中出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    debug_enhanced_lstm_crf_prediction()